/**   
* @Title: GreetingController.java
* @Package me.websocket.controller
* @Description: TODO
* @author xaoyaoyao
* @date Jan 24, 2019 5:00:01 PM
* @version V1.0   
*/
package me.websocket.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.util.HtmlUtils;

import me.websocket.dto.Greeting;
import me.websocket.dto.HelloMessage;

/**
 * @ClassName: GreetingController
 * @Description: TODO
 * @author xaoyaoyao
 * @date Jan 24, 2019 5:00:01 PM
 * 
 */
@Controller
public class GreetingController {

	/**
	 * websochet消息发送对象
	 */
	@Autowired
	private SimpMessagingTemplate messagingTemplate;

	// 测试页面显示后台消息推送次数
	private int count = 0;

	@MessageMapping("/hello")
	@SendTo("/topic/greetings")
	public Greeting greeting(HelloMessage message) throws Exception {
		return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
	}

	// 由后台发送到浏览器服务
	@SendTo("/topic/callback")
	// 定时5秒给页面推一次数据
	@Scheduled(cron = "0/5 * * * * ?")
	public Object callback() throws Exception {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date = df.format(new Date());
		System.out.println(">>>>>>>>>>>>>>>>>>>> 推送消息了 >> " + date);
		// 向页面这个地址推送消息
		messagingTemplate.convertAndSend("/topic/callback", "客户端消息" + count + ", 时间 >> " + date);
		count++;
		return null;
	}
}
